package com.zmj.framework.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zmj.amc.sdk.entity.User;
import com.zmj.framework.authorization.vo.UserAccess;
import com.zmj.framework.common.CommonConstant;

import java.util.HashMap;
import java.util.Map;

public class ThreadContextHandler {
    public static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key){
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void setToken(String token){
        set(CommonConstant.CONTEXT_KEY_USER_TOKEN,token);
    }

    public static String getToken(){
        Object value = get(CommonConstant.CONTEXT_KEY_USER_TOKEN);
        return StrUtil.toString(value);
    }

    public static void setFirstLoginFlag(String username) {
        if(StrUtil.isBlank(username)) {
            return;
        }
        set(username,true);
    }

    public static boolean getFirstLoginFlag(String username){
        Object value = get(username);
        if(ObjectUtil.isNull(value)) {
            return false;
        }
        return BooleanUtil.toBoolean(StrUtil.toString(value));
    }
    private static String returnObjectValue(Object value) {
        return value==null?null:value.toString();
    }

    public static void setCurrentUser(User user) {
        set(CommonConstant.CONTEXT_KEY_USER,user);
    }

    public static User getCurrentUser() {
        Object value = get(CommonConstant.CONTEXT_KEY_USER);
        if (value == null) {
            return new User();
        }
        return BeanUtil.toBean(value,User.class);
    }

    public static void remove(){
        threadLocal.remove();
    }

}
